#include "engine.h"
#include "indexbuffer.h"
#include <gl/glew.h>

indexbuffer_t::indexbuffer_t()
{
	hwid=0xffffffff;
	numindices=0;
}

indexbuffer_t::indexbuffer_t(uint32 indexnum)
{
	init(indexnum);
}

void indexbuffer_t::init(uint32 bufsize)
{
	release();
	numindices=bufsize;
	glGenBuffers(1,&hwid);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,hwid);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER,bufsize*sizeof(uint16),NULL,GL_STATIC_DRAW);
}

uint16* indexbuffer_t::lock()
{
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,hwid);
	return (uint16*)glMapBuffer(GL_ELEMENT_ARRAY_BUFFER,GL_WRITE_ONLY);
}

uint16* indexbuffer_t::lock_read()
{
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,hwid);
	return (uint16*)glMapBuffer(GL_ELEMENT_ARRAY_BUFFER,GL_READ_ONLY);
}

void indexbuffer_t::unlock()
{
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,hwid);
	glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
}

void indexbuffer_t::release()
{
	if (hwid==0xffffffff)
		return;
	glDeleteBuffers(1,&hwid);
	hwid=0xffffffff;
}


indexbuffer_t::~indexbuffer_t()
{
	release();
}

void indexbuffer_t::set()
{
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,hwid);
}